/**
 * Created by 83617 on 2019/1/11.
 */
var Society = require('../models/society')
var _ = require('underscore')
var fs = require('fs')
var path = require('path')

exports.societyDetails = function(req,res){
    Society.fetch(function(err,societies){
        if(err) console.log(err)
        res.render('detail',{
            title: '社团信息',
            societies: societies
        })
    })
}

exports.toSocietyInsertPage = function(req,res){
    res.render('adminSociety',{
        title: '社团录入',
        society:{
            name:'',
            num:'',
            master:'',
            //icon:'',
            detail:''
        }
    })
}

//update society
exports.updateSociety = function(req,res){
    var id = req.params.id
    Society.findOneById(id,function(err,society){
        if(err) console.log(err)
        res.render('adminSociety',{
            title:'社团录入',
            society:society
        })
    })
}

//判断是否上传图片
exports.saveIcon = function(req,res,next){
    var iconData = req.files.uploadIcon
    var filePath = iconData.path
    var originalFilename = iconData.originalFilename
    //如果有图片上传
    if(originalFilename){
        fs.readFile(filePath,function(err,data){
            var timeStamp = Date.now()
            var type = iconData.type.split('/')[1]
            var icon = timeStamp + '.' + type
            var newPath = path.join(__dirname,'../../','bower_components/resorce/uploadIcon/' + icon)
            fs.writeFile(newPath,data,function(err){
                req.icon = icon
                next()
            })
        })
    }else{
        next()
    }
}

exports.updateSocietyFunc = function(req,res){
    var societyObj = req.body.society
    var icon
    if(req.icon){
        icon = req.icon
        societyObj.icon = icon
    }
    var _society;
    if(societyObj._id !== "undefined"){
        Society.findOneById(societyObj._id,function(err,society){
            if(err) console.log(err)
            _society = _.extend(society,societyObj)
            _society.save(function(err,society){
                if(err) console.log(err)
                res.redirect('/')
            })
        })
    }else{
        _society = new Society({
            name: societyObj.name,
            num: societyObj.num,
            master: societyObj.master,
            //icon: societyObj.icon,
            icon: icon,
            detail: societyObj.detail
        })
        _society.save(function(err, society) {
            if (err) console.log(err)
            res.redirect('/admin/society')
        })
    }
}

exports.deleteSociety = function(req,res){
    var id = req.query.id
    Society.deleteById(id,function(err,society){
        if(err){console.log(err)}
        else{
            res.json({success:1, name:society.name})
        }
    })
}